package com.iqilu.ksd.service;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.iqilu.ksd.R;
import com.iqilu.ksd.utils.CacheUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by Coofee on 2016/12/5.
 */

public class UpdateService extends Service {

    private static final String TAG = "UpdateService";

    private String url;
    private NotificationManager manager;
    private Notification.Builder builder;

    private int mTotal = 100;
    private int mProgress = 0;

    private Timer timer;
    private TimerTask timerTask;

    private static final int NOTIFICATION_FLAG = 2002;

    @Override
    public void onCreate() {
        super.onCreate();
        builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.update_title))
                .setSmallIcon(R.mipmap.ic_launcher);
        timer = new Timer();
        timerTask = new TimerTask() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void run() {
                updateNotification(mTotal,mProgress);
            }
        };
        timer.schedule(timerTask,1000,1000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null){
            url = intent.getStringExtra("url");
            downLoad();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void downLoad() {
        String path = CacheUtils.getCacheDir(this);
        String name = "" + System.currentTimeMillis() + ".apk";
        OkHttpUtils.get().url(url).tag(this).build().execute(new FileCallBack(path, name) {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @SuppressLint({"StringFormatInvalid", "StringFormatMatches"})
            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                mProgress = (int) (total * progress);
                mTotal = (int) total;
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                stop();
            }

            @Override
            public void onResponse(File response, int id) {
                Log.i(TAG,"onResponse...");
//                stop();
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
                startActivity(i);
                stopSelf();
            }
        });
    }

    private void stop(){
        if(timer != null){
            timer.cancel();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void updateNotification(int total, int progress){
        builder.setProgress(total,progress,false);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_NO_CLEAR;
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_FLAG, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stop();
        manager.cancel(NOTIFICATION_FLAG);
    }
}
